<?php

namespace Iwesen\Sem\Track\Advertisers;

use Illuminate\Support\Facades\Log;

class Kuaishou
{
    protected $api =  "https://ad.e.kuaishou.com/ads/js-convert-check/activate";

    public function callback($param)
    {
        if(!isset($param['eventType']) || !$param['eventType']){
            $param['eventType'] = config('sem-track.kuaishou.eventType');
            if(!$param['eventType']){
                throw new \Exception( 'eventType does not exist in parameter !');
            }
        }
        if(!isset($param['convertId']) || !$param['convertId']){
            $param['convertId'] = config('sem-track.kuaishou.convertId');
            if(!$param['convertId']){
                throw new \Exception( 'convertId does not exist in parameter !');
            }
        }

        if(!isset($param['uniqueKey'])){
            throw new \Exception( 'uniqueKey does not exist in parameter !');
        }

        $formData=[
            'eventType'=>$param['eventType'],
            'convertId'=>$param['convertId'],
            'uniqueKey'=>$param['uniqueKey'],
        ];

        $header=[
            'Content-Length:'.strlen(http_build_query($formData)),
            'Host:ad.e.kuaishou.com',
            'Accept:*/*',
            'Content-Type: application/x-www-form-urlencoded; charset=utf-8'
        ];
        try {
            $result = (new Request())->_request($this->api,$header,$formData,true);
            $data = json_decode($result,true);
            $status = $data['result'];
            if ($status === 1) {
                return 'success';
            }
            return 'fail';
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }
    }
}